package com.timepies.database;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;

public class SQLiteDao extends SQLiteOpenHelper {

	public SQLiteDao(Context context) {
		super(context, Constants.DBNAME, null, Constants.DBVERSION);
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		String q = "CREATE TABLE " + Constants.TBL_NAME
				+ " ( _id INTEGER PRIMARY KEY AUTOINCREMENT,"
				+ Constants.FIELD_SUBJECT + " TEXT," + Constants.FIELD_TEXT
				+ " TEXT," + Constants.FIELD_DATE + " TEXT)";
		db.execSQL(q);
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
	}

	// public methods

	public void save(String sub, String txt, String date) {
		SQLiteDatabase db = getWritableDatabase();

		ContentValues cv = new ContentValues();
		cv.put(Constants.FIELD_SUBJECT, sub);
		cv.put(Constants.FIELD_TEXT, txt);
		cv.put(Constants.FIELD_DATE, date);
		try {
			db.insert(Constants.TBL_NAME, null, cv);
		} catch (SQLiteException sqle) {
			// Gestione delle eccezioni
		}
	}

	public void update(String sub, String txt, String date, long id) {
		SQLiteDatabase db = getWritableDatabase();

		ContentValues cv = new ContentValues();
		cv.put(Constants.FIELD_SUBJECT, sub);
		cv.put(Constants.FIELD_TEXT, txt);
		cv.put(Constants.FIELD_DATE, date);
		try {
			db.update(Constants.TBL_NAME, cv, Constants.FIELD_ID + "=?",
					new String[] { Long.toString(id) });
		} catch (SQLiteException sqle) {
			// Gestione delle eccezioni
		}
	}

	public boolean delete(long id) {
		SQLiteDatabase db = getWritableDatabase();
		try {
			if (db.delete(Constants.TBL_NAME, Constants.FIELD_ID + "=?",
					new String[] { Long.toString(id) }) > 0)
				return true;
			return false;
		} catch (SQLiteException sqle) {
			return false;
		}

	}

	public Cursor cursor() {
		Cursor crs = null;
		try {
			SQLiteDatabase db = getReadableDatabase();
			crs = db.query(Constants.TBL_NAME, null, null, null, null, null,
					null, null);
		} catch (SQLiteException sqle) {
			return null;
		}
		return crs;
	}

}
